import {cfg} from "./config";

class Login {
    private cookie: string = ''

    async login() {
        const form = new FormData();
        form.append('account', cfg.account);
        form.append('password', cfg.passwd);
        const res = await fetch(`${cfg.server}/user/login`, {
            method: 'POST',
            body: form
        });

        if (!res.ok) {
            throw new Error(res.statusText)
        }
        const data = await res.json()
        if (data.state !== 0) {
            throw new Error(data.msg)
        }
        res.headers.forEach((v, k) => {
            if (k === 'set-cookie') {
                const s = v.split(';').filter((v) => {
                    return v.indexOf('session') === 0
                })
                if (s.length > 0) {
                    this.cookie += s + "; "
                }
            }
        })
        console.log('login success', this.cookie);
        return
    }

    async getCookie() {
        if (!this.cookie) {
            await this.login();
        }
        return this.cookie;
    }
}

export const login = new Login();
